package observer;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * These longs can be observed by {@link LongObserver}s, i.e. the observers will be notified of any changes.
 *
 * @author Neil Dickson
 */
public final class ObservedLong implements Copiable<ObservedLong>, Serializable {
	private long					value;
	private ArrayList<LongObserver>	observers;

	public ObservedLong(long i) {
		value = i;
		observers = null;
	}

	public synchronized void addObserver(LongObserver observer) {
		if (observer==null) {
			throw new NullPointerException();
		}
		if (observers==null) {
			observers = new ArrayList<LongObserver>();
		}
		observers.add(observer);
	}
	public synchronized void removeObserver(LongObserver observer) {
		if (observers!=null && observers.contains(observer)) {
			observers.remove(observer);
		}
	}

	public long get() {
		return value;
	}
	public void set(long i) {
		set(null,i);
	}
	public void set(LongObserver culprit,long i) {
		value = i;
		updateAllBut(culprit);
	}

	public String toString() {
		return Long.toString(value);
	}

	public ObservedLong copy() {
		return new ObservedLong(value);
	}

	private void updateAllBut(LongObserver culprit) {
		if (observers!=null) {
			for (LongObserver observer : observers) {
				if (observer!=culprit) {
					observer.valueChanged(this);
				}
			}
		}
	}
}
